#include "connect_main.h"
#include "ui_connect_main.h"
#include <QProcess>
#include <QDebug>
#include <QRegularExpression>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include "filetransferdialog.h"

connect_Main::connect_Main(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::connect_Main)
{
    ui->setupUi(this);
    // 连接按钮的点击信号到对应的槽函数
    connect(ui->collaborationButton, &QPushButton::clicked, this, [this]() {
        ui->stackedWidget->setCurrentIndex(0); // 切换到第一个页面
    });

    connect(ui->loggerButton, &QPushButton::clicked, this, [this]() {
        ui->stackedWidget->setCurrentIndex(1); // 切换到第二个页面
    });
}

connect_Main::~connect_Main()
{
    delete ui;
}

void connect_Main::on_collaborationButton_clicked()
{

}

void connect_Main::on_loggerButton_clicked()
{

}

//ip地址输入
void connect_Main::on_lineEdit_editingFinished()
{

}

//通过IP地址连接远程桌面
void connect_Main::on_startconnect_clicked()
{
    QString ip = ui->lineEdit->text().trimmed();
    QString user = ui->username->text().trimmed();
    QString pass = ui->password->text();

    // 验证IP格式
    QRegularExpression ipRegex(R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)");
    if (!ipRegex.match(ip).hasMatch()) {
        QMessageBox::warning(this, "错误", "无效的IP地址格式");
        return;
    }

    if (user.isEmpty() || pass.isEmpty()) {
        QMessageBox::warning(this, "错误", "用户名和密码不能为空");
        return;
    }

    // 使用xfreerdp连接
    QProcess *process = new QProcess(this);
    QString program = "xfreerdp";
    QStringList arguments = {
        "/v:" + ip,
        "/u:" + user,
        "/p:" + pass,
        "/cert:ignore",  // 忽略证书警告
        "+clipboard",
        "/dynamic-resolution"
    };

    // 连接信号处理输出
    connect(process, &QProcess::readyReadStandardError, [process, this]() {
        QByteArray err = process->readAllStandardError();
        qDebug() << "错误: " << err;
    });

    connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [this, ip](int exitCode, QProcess::ExitStatus status) {
        if (exitCode != 0 || status == QProcess::CrashExit) {
            qDebug() << QString("连接到 %1 失败！错误码：%2").arg(ip).arg(exitCode);

        } else {
            qDebug() << QString("已断开与 %1 的连接").arg(ip);
        }
    });

    // 启动进程
    process->start(program, arguments);
    if (!process->waitForStarted(3000)) {
        QMessageBox::critical(this, "错误", "无法启动远程桌面客户端！错误信息: " + process->errorString());
        delete process; // 释放资源
        return;
    }

}

void connect_Main::on_pushButton_clicked()
{
    // 创建FileTransferDialog实例并显示
    FileTransferDialog *fileTransferDialog = new FileTransferDialog(this);
    fileTransferDialog->show();
}

